﻿using System.Collections.Generic;

namespace TopHero
{
    public class MessageDispatcher : Singleton<MessageDispatcher>
    {
        private readonly List<Telegram> _priorityQ = new List<Telegram>();

        void Discharge(BaseEntity receiver, Telegram msg)
        {
            if (!receiver.HandleMessage(msg))
            {
                //Debug.Log("!receiver.HandleMessage(msg)");
            }
        }

        internal void DispatchMsg(float delay, int sender, int receiver, int msg, object extraInfo = null)
        {
            BaseEntity rEntity = EntityManager.Instance.GetEntityFromID(receiver);

            if (rEntity == null)
            {
                Debug.LogError("rEntity == null");
                return;
            }

            Telegram telegram = new Telegram(sender, receiver, msg, 0, extraInfo);

            if (delay <= 0.0f)
            {
                Discharge(rEntity, telegram);
            }
            else
            {
                float currentTime = TickCounter.Instance.currentTime;
                telegram.dispatchTime = currentTime + delay;
                _priorityQ.Add(telegram);
            }
        }

        internal void DispatchDelayedMessages()
        {
            float currentTime = TickCounter.Instance.currentTime;

            for (int i = _priorityQ.Count - 1; i >= 0; i--)
            {
                Telegram t = _priorityQ[i];
                if (t.dispatchTime < currentTime && t.dispatchTime > 0)
                {
                    BaseEntity receiver = EntityManager.Instance.GetEntityFromID(t.receiver);

                    Discharge(receiver, t);
                    _priorityQ.RemoveAt(i);
                }
            }
        }

        internal void Reset()
        {
            _priorityQ.Clear();
        }
    }
}